Page({
  data: {
    tasks: [],
    newTaskName: '', // 新任务的名称
    newTaskIcon: '',  // 新任务的图标路径
    allTasksCount: 0,
    morningTasksCount: 0,
    noonTasksCount: 0,
    afternoonTasksCount: 0,
    eveningTasksCount: 0,
    anytimeTasksCount: 0
  },

  onLoad() {
    // this.updateWeekDays();
    this.loadTasks();
  },

  loadTasks() {
    wx.cloud.callFunction({
      name: 'getTasks',
      success: res => {
        this.setData({
          tasks: res.result.data
        });
      },
      fail: err => {
        console.error('[云函数] [getTasks] 调用失败：', err);
      }
    });
  },

  addTask() {
    wx.showModal({
      title: '添加计划',
      placeholderText: '请输入计划名称',
      editable: true,
      success: res => {
        if (res.confirm) {
          const newTask = {
            name: res.content,
            icon: '../../images/信息 (2).png',
            // time: this.getCurrentDate(),
            time:"12",
            days: 0,
            logs: 0
          };
          wx.cloud.callFunction({
            name: 'addTask',
            data: newTask,
            success: () => {
              this.loadTasks();
            },
            fail: err => {
              console.error('[云函数] [addTask] 调用失败：', err);
            }
          });
        }
      }
    });
  },

  viewTaskDetails(event) {
    const taskId = event.currentTarget.dataset.id;
    const task = this.data.tasks.find(t => t._id === taskId);
    if (task) {
      wx.showModal({
        title: `任务详情 - ${task.name}`,
        content: `累计打卡天数：${task.days}\n日志：${task.logs}`,
        editable: true,
        placeholderText: '请输入日志内容',
        showCancel: true,
        cancelText: '打卡+1',
        confirmText: '增加日志',
        success: res => {
          if (res.cancel) {
            task.days += 1;
          }
          if (res.confirm && res.content) {
            task.logs += 1;
          }
          wx.cloud.callFunction({
            name: 'updateTask',
            data: task,
            success: () => {
              this.loadTasks();
            },
            fail: err => {
              console.error('[云函数] [updateTask] 调用失败：', err);
            }
          });
        }
      });
    }
  },

  deleteTask(event) {
    const taskId = event.currentTarget.dataset.id;
    wx.cloud.callFunction({
      name: 'deleteTask',
      data: { _id: taskId },
      success: () => {
        this.loadTasks();
      },
      fail: err => {
        console.error('[云函数] [deleteTask] 调用失败：', err);
      }
    });
  }
});